package cn.jbolt.core.poi.word;

import cn.hutool.core.io.FileUtil;
import cn.jbolt.core.enjoy.directive.*;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import com.jfinal.template.ext.directive.NowDirective;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * JBoltWord工具类
 *
 * @ClassName: JBoltWordUtil
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2021年2月14日
 */
public class JBoltWordUtil {
	private static final String ENGINE_NAME = "jbolt_word_tpl";
	public static final JBoltWordUtil me = new JBoltWordUtil();
	private Engine engine;
	private JBoltWordUtil(){
		engine = Engine.create(ENGINE_NAME);
		engine.setDevMode(true);
		engine.setStaticFieldExpression(true);
		engine.setStaticMethodExpression(true);
		engine.addDirective("now", NowDirective.class, true);
		engine.addDirective("imgUrlToBase64", ImageUrlToBase64Directive.class);
		engine.addDirective("imgPathToBase64", ImagePathToBase64Directive.class);
		engine.addDirective("sex", SexDirective.class);
		engine.addDirective("fileSizeFormatter", FileSizeFormatterDirective.class);
		engine.addDirective("boolToStr", BooleanToStrDirective.class);
		engine.addDirective("enable", EnableDirective.class);
		engine.addDirective("datetime", DateTimeDirective.class);
	}

	/**
	 * 获取byte[]数据
	 *
	 * @param jBoltWord
	 * @return
	 */
	public byte[] getWordBytes(JBoltWord jBoltWord) {
		String xmlTplContent = FileUtil.readUtf8String(jBoltWord.getTplFile());
		Template tpl = engine.setEncoding("utf-8").getTemplateByString(xmlTplContent);
		String result = tpl.renderToString(jBoltWord.getDatas());
		return result.getBytes(StandardCharsets.UTF_8);
	}

	/**
	 * 保存到文件
	 *
	 * @param jBoltWord
	 * @param saveFilePath
	 * @return
	 */
	public File saveFile(JBoltWord jBoltWord, String saveFilePath) {
		return FileUtil.writeBytes(jBoltWord.toByteArray(), saveFilePath);
	}
}
